package com.p2p.user.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.p2p.common.base.BaseController;
import com.p2p.common.cache.CacheManager;
import com.p2p.common.constants.Message;
import com.p2p.common.enums.ResponseEnum;
import com.p2p.user.po.Permission;
import com.p2p.user.po.Role;
import com.p2p.user.po.RolePermission;
import com.p2p.user.service.PermissionService;
import com.p2p.user.service.RolePermissionService;
import com.p2p.user.service.RoleService;
import com.p2p.user.vo.PermissionVo;



/**
 * Created by Allen on 2017/3/19.
 */
@RestController
@RequestMapping(value = "role")
public class RoleController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private PermissionService permissionService;
    
    
    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 获取用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectRoleOption", method = RequestMethod.GET)
    public Message selectRoleOption(HttpServletRequest request) {
       
        List<Role> roleList = roleService.selectList(new EntityWrapper<Role>().eq("status",1));
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), roleList);
    }

    /**
     * 获取用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectRole", method = RequestMethod.GET)
    public Map selectRole(HttpServletRequest request) {
        
        List<Role> roleList = roleService.selectList(new EntityWrapper<Role>().eq("status",1));
        Map result = new HashMap();
        result.put("rel", true);
        result.put("msg", "SUCCESS");
        result.put("list", roleList);
        result.put("count", roleList.size());
        return result;
    }
    /**
     * 获取角色信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectRoleInfo", method = RequestMethod.GET)
    public Message selectRoleInfo(HttpServletRequest request) {
      
        Long roleId = getRoleId();
        Role role = roleService.selectOne(new EntityWrapper<Role>().eq("id", roleId));
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), role);
    }


    /**
     * 删除角色
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "deleteRole", method = RequestMethod.GET)
    public Message deleteRole(HttpServletRequest request) {
        Long roleId = Long.parseLong(request.getParameter("roleId"));
        Role role = roleService.selectById(roleId);
        role.setStatus(-1);
        roleService.updateById(role);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 获取角色 By RoleId
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectRoleById", method = RequestMethod.GET)
    public Message selectRoleById(HttpServletRequest request) {
       
        List<PermissionVo> permissionVoList = permissionService.selectPermissionVo();
        Long roleId = Long.parseLong(request.getParameter("roleId"));
        CacheManager cacheManager = CacheManager.getInstance();
        List<Permission> permissions = (List<Permission>) cacheManager.getCache(roleId);
        if (permissions == null) {
            permissions = permissionService.selectPermissionByRoleId(roleId);
            cacheManager.addCache(roleId, permissions);
        }
        List<Permission> finalPermissions = permissions;
        permissionVoList.stream().forEach(permissionVo -> {
            finalPermissions.stream().forEach(permission -> {
                if (permission.getId() == permissionVo.getId()) {
                    permissionVo.setChecked(true);
                }
            });
            if (permissionVo.getType() == 1) {
                permissionVo.setChecked(true);
                permissionVo.setChkDisabled(true);
            }

        });
        Role role = roleService.selectOne(new EntityWrapper<Role>().eq("id", roleId));
        Map result = new HashMap();
        result.put("role", role);
        result.put("permission", permissionVoList);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
    }


    /**
     * 更新角色 角色权限
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "updateRole", method = RequestMethod.POST)
    public Message updateRole(HttpServletRequest request) {
       
        Long roleId = Long.parseLong(request.getParameter("roleId"));
        String roleName = request.getParameter("roleName");
        Integer roleType = Integer.parseInt(request.getParameter("roleType"));
        String ids = request.getParameter("ids");

        Role role = roleService.selectById(roleId);
        role.setId(roleId);
        role.setName(roleName);
        role.setRoleType(roleType);
        roleService.updateById(role);

        List<RolePermission> list = new ArrayList();
        Arrays.asList(ids.split(",")).forEach(id -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(Long.parseLong(id));
            rolePermission.setRoleId(roleId);
            rolePermission.setCreateTime(new Timestamp(System.currentTimeMillis()));
            rolePermission.setStatus(1);
            list.add(rolePermission);
        });
        rolePermissionService.delete(new EntityWrapper<RolePermission>().eq("role_id", roleId));
        rolePermissionService.insertBatch(list);
        CacheManager cacheManager = CacheManager.getInstance();
        cacheManager.removeCache(roleId);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 获取用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "insertRole", method = RequestMethod.POST)
    public Message insertRole(HttpServletRequest request) {
       
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String roleName = request.getParameter("roleName");
        Integer roleType = Integer.parseInt(request.getParameter("roleType"));
        String ids = request.getParameter("ids");
        Role role = new Role();
        role.setName(roleName);
        role.setRoleType(roleType);
        role.setStatus(1);
        role.setCreateTime(timestamp);
        roleService.insert(role);
        Long roleId = role.getId();
        List<RolePermission> list = new ArrayList();
        Arrays.asList(ids.split(",")).forEach(id -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(Long.parseLong(id));
            rolePermission.setRoleId(roleId);
            rolePermission.setCreateTime(new Timestamp(System.currentTimeMillis()));
            rolePermission.setStatus(1);
            list.add(rolePermission);
        });
        rolePermissionService.delete(new EntityWrapper<RolePermission>().eq("role_id", roleId));
        rolePermissionService.insertBatch(list);
        CacheManager cacheManager = CacheManager.getInstance();
        cacheManager.removeCache(roleId);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }
}
